package cn.itcast.controller.log;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;

    @Autowired
    private SysLogService sysLogService;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable{
        Object result = null;


            result = pjp.proceed();// 执行原方法
            SysLog sysLog = new SysLog();
            sysLog.setId(UUID.randomUUID().toString());
            sysLog.setTime(new Date());

            String ip = request.getRemoteAddr();
            sysLog.setIp(ip);
            User user = (User) session.getAttribute("loginUser");
            if(user!=null){
                sysLog.setUserName(user.getUserName());
                sysLog.setCompanyId(user.getCompanyId());
                sysLog.setCompanyName(user.getCompanyName());
            }


            MethodSignature signature = (MethodSignature) pjp.getSignature(); //获取方法签名 方法+注解
            Method method = signature.getMethod(); //获取方法
            sysLog.setMethod(method.getName()); //当前方法名称

           if(method.isAnnotationPresent(RequestMapping.class)){
               RequestMapping annotation = method.getAnnotation(RequestMapping.class);
               sysLog.setAction(annotation.name()); //取的是方法上@RequestMapping注解中name属性对应的值
           }
            sysLogService.save(sysLog);


        return result;

    }


}
